﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Domain.Abstract;
using Domain.Entity;

namespace Domain.Concrete
{
    public class EFAccountRepository : IAccountRepository
    {
        public IQueryable<Account> Accounts
        {
            get { return Context.Accounts; }
        }

        public EFDbContext Context { get; set; }

        public EFAccountRepository()
        {
            Context = EFDbContext.Instance;
        }

        public EFAccountRepository(EFDbContext context)
        {
            Context = context;
        }

        public void SaveAccount(Account account)
        {
            if (account.Id == 0)
                Context.Accounts.Add(account);
            else
                Context.Entry(account).State = EntityState.Modified;
            Context.SaveChanges();
        }

        public void DeleteAccount(Account account)
        {
            var dbAccount = Accounts.SingleOrDefault(x => x.Id == account.Id);

            if (dbAccount != null)
                Context.Accounts.Remove(dbAccount);
            Context.SaveChanges();
        }

        public Account FindAccount(int id)
        {
            return Accounts.FirstOrDefault(x => x.Id == id); 
        }

        public Account FindAccountByUsername(string username)
        { 
            return Accounts.FirstOrDefault(x => x.Username.Equals(username));
        }
    }
}
                                               